package com.ja.openchat.ui.chat.group;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityMoreMemberBinding;
import com.ja.openchat.ui.chat.group.adapter.MemberGridAdapter;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.ja.openchat.viewmodels.MoreMemberViewModel;
import com.ja.openchat.views.ChatUserDialog;
import com.ja.openchat.views.CustomEditText;
import com.lxj.xpopup.XPopup;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.SuperGroupFullInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;

public class MoreMemberActivity extends BaseFragment<ActivityMoreMemberBinding, MoreMemberViewModel> {

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.activity_more_member;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    public static void start(Context context,ChatInfo chatInfo,SuperGroupInfo super_groupInfo,SuperGroupFullInfo super_groupFullInfo){
        Intent intent = new Intent(context,MoreMemberActivity.class);
        intent.putExtra("chat",chatInfo);
        intent.putExtra(BUNDLE_SUPER_GROUPINFO,super_groupInfo);
        intent.putExtra(BUNDLE_SUPERGROUP_FULLINFO,super_groupFullInfo);
        context.startActivity(intent);
    }

    public static final String BUNDLE_SUPERGROUP_FULLINFO = "SuperGroupFullInfo";
    public static final String BUNDLE_SUPER_GROUPINFO = "super_groupInfo";

    public SuperGroupFullInfo super_groupFullInfo;
    private List<GroupMemberInfo> membersList = new ArrayList<>();
    private List<GroupMemberInfo> orgi_membersList = new ArrayList<>();
    private List<GroupMemberInfo> orgi_memberIsManagersList = new ArrayList<>();
    public MemberGridAdapter memberGridAdapter;
    public ChatInfo chatInfo, chatInfo2;
    public SuperGroupInfo super_groupInfo;


    @Override
    public void initView() {
        super.initView();
        Bundle arguments = getArguments();
        if(arguments==null){
            getActivity().finish();
            return;
        }
        viewModel.setFragment(this,binding.recyclerView);
        super_groupFullInfo = arguments.getParcelable(BUNDLE_SUPERGROUP_FULLINFO);
        if(super_groupFullInfo==null){
            getActivity().finish();
            return;
        }
        super_groupInfo = arguments.getParcelable(BUNDLE_SUPER_GROUPINFO);
        if(super_groupInfo==null){
            return;
        }
        chatInfo = arguments.getParcelable("chat");
        if(chatInfo==null){
            chatInfo = new ChatInfo();
        }
        chatInfo2 = arguments.getParcelable("chat2");
        if(chatInfo2==null){
            chatInfo2 = new ChatInfo();
        }

        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.finish();
            }
        });
        binding.toolbar.tvBarTitle.setText(String.format(getString(R.string.chat_members_format), super_groupFullInfo.member_count));

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 5);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        memberGridAdapter = new MemberGridAdapter(R.layout.adapter_grid_member, membersList);
        binding.recyclerView.setAdapter(memberGridAdapter);
        memberGridAdapter.setOnItemClickListener((adapter, view1, position) -> {
            GroupMemberInfo member = membersList.get(position);
            clickMember(member, false);
        });
        getSuperMembers();
        getSuperAdminMembers();
        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });
    }

    public void doSearch(String keyword){
        if(TextUtils.isEmpty(keyword)){
            resetMembersListUI();
            return;
        }
        membersList.clear();
        for (int i = 0; i < orgi_membersList.size(); i++) {
            GroupMemberInfo member = orgi_membersList.get(i);
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
            if(user!=null&&user.isMatch(keyword)){
                membersList.add(member);
            }else{
                String dispN = UserInfo.userDisplayName(member.user_id);
                if(!TextUtils.isEmpty(dispN)&&dispN.contains(keyword)){
                    membersList.add(member);
                }
            }
        }
        memberGridAdapter.notifyDataSetChanged();
    }

    public void getSuperAdminMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(getActivity(), chatInfo.id,chatInfo.superGroupId(), "supergroupMembersFilterAdministrators", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    orgi_memberIsManagersList.clear();
                    if (obj.size() > 0) {
                        orgi_memberIsManagersList.addAll(obj);
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private void resetMembersListUI() {
        membersList.clear();
        membersList.addAll(orgi_membersList);
        if (canInvideMember()) {
            membersList.add(GroupMemberInfo.optAdd());
        }
        if (canEditGroupSetting()) {
            membersList.add(GroupMemberInfo.optDel());
        }
        memberGridAdapter.notifyDataSetChanged();
    }

    private boolean canEditGroupSetting() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Administrator:
                    //管理员
                    return true;
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                case GroupMemberState_Left:
                    //不在群组
                    break;
                case GroupMemberState_Member:
                    //普通成员
                    break;
                case GroupMemberState_Banned:
                    //被禁用
                    break;
                case GroupMemberState_Restricted:
                    //被禁言
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    public void getSuperMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(getActivity(),chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterRecent", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    orgi_membersList.clear();
                    if (obj.size() > 0) {
                        orgi_membersList.addAll(obj);
                    }
                    refreshMembersListUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }


    private boolean canInvideMember() {
        boolean canInvide = canEditGroupSetting();
        if (canInvide) {
            return canInvide;
        }
        return chatInfo.permissions != null && chatInfo.permissions.can_invite_users;
    }

    private void clickMember(GroupMemberInfo member, boolean isManager) {
        if (member.isOptAdd()) {
            if (isManager) {//增加管理员
                ContactChooseActivity.startWithAddManager(getActivity(), chatInfo.id, orgi_membersList, orgi_memberIsManagersList);
            } else {//增加成员
                ContactChooseActivity.startWithInviteMember(getActivity(), chatInfo.id, orgi_membersList);
            }
        } else if (member.isOptDel()) {
            if (isManager) {//删除管理员
                ContactChooseActivity.startWithRemoveManager(getActivity(), chatInfo.id, orgi_memberIsManagersList);
            } else {//删除成员
                ContactChooseActivity.startWithRemoveMember(getActivity(), chatInfo.id, orgi_membersList, orgi_memberIsManagersList);
            }
        } else {
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
            if (user == null) return;
            if (member.user_id == UserInfo.getUserInfo().id) {
//                ProfileActivity.start(this);
                startContainerActivity(PersonalDataFragment.class.getCanonicalName());
            } else {
//                if (super_groupInfo != null && super_groupInfo.status != null) {
//                    TelegramManager.GroupMemberState state = super_groupInfo.status.getMemberState();
//                    if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
//                        ContactDetailActivity.start(getActivity(), user, chatInfo.id, true);
//                    }
////                    else {
////                        ContactDetailActivity.start(getActivity(), user, !(chatInfo.permissions != null && !chatInfo.permissions.banWhisper));
////                    }
//                }
//                if (chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper) {
//                    ContactDetailActivity.start(getActivity(), user, !(chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper));
//                }

                boolean blockContact = !(chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper);
                new XPopup.Builder(getActivity())
                        .hasShadowBg(true)
                        .isDestroyOnDismiss(true)
                        .dismissOnTouchOutside(true)
                        .borderRadius(10)
                        .atView(binding.recyclerView)
                        .asCustom(new ChatUserDialog(getActivity(), user,blockContact, new ChatUserDialog.OnItemClickListner() {
                            @Override
                            public void clickPostion(int postion, ChatInfo chatInfo) {

                            }
                        })).show();
            }
        }
    }

    public void refreshMembersListUI(){
        if(TextUtils.isEmpty(binding.etSearch.getText())){
            resetMembersListUI();
            return;
        }
        doSearch(binding.etSearch.getText().toString());
    }


}
